package com.freewater.library.lending.book.infrastructure.repository;

import com.freewater.library.lending.book.infrastructure.dao.BookInstanceDao;
import com.freewater.library.lending.book.infrastructure.po.BookInstancePo;
import com.freewater.library.lending.book.model.BookInstance;
import com.freewater.library.lending.book.model.BookInstanceRepository;
import lombok.RequiredArgsConstructor;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RequiredArgsConstructor
public class BookInstanceRepositoryImpl implements BookInstanceRepository {

    private final BookInstanceDao bookInstanceDao;

    @Override
    public void save(BookInstance bookInstance) {
        this.bookInstanceDao.save(new BookInstancePo(bookInstance));
    }

    @Override
    public boolean exists(String qrCode) {
        return this.bookInstanceDao.existsByQrCode(qrCode);
    }

    @Override
    public Optional<BookInstance> findById(String qrCode) {
        Optional<BookInstancePo> recordOpt = this.bookInstanceDao.findByQrCode(qrCode);
        return recordOpt.map(BookInstancePo::convert);
    }

    @Override
    public List<BookInstance> findCanBeReservedBooks(String isbn) {
        List<BookInstancePo> records = this.bookInstanceDao.findCanBeReservedBooks(isbn);
        return records.stream().map(BookInstancePo::convert).collect(Collectors.toList());
    }

    @Override
    public List<BookInstance> findReservingBooks() {
        List<BookInstancePo> records = this.bookInstanceDao.findReservingBooks();
        return records.stream().map(BookInstancePo::convert).collect(Collectors.toList());
    }

    @Override
    public List<BookInstance> findCheckingOutBooksNotMarkedOverdue() {
        List<BookInstancePo> records = this.bookInstanceDao.findCheckingOutBooksNotMarkedOverdue();
        return records.stream().map(BookInstancePo::convert).collect(Collectors.toList());
    }

    @Override
    public void delete(BookInstance bookInstance) {
        this.bookInstanceDao.delete(new BookInstancePo(bookInstance));
    }
}


